package com.linjiahao.nettyTwo.handler;

import com.alibaba.fastjson.JSON;
import com.linjiahao.nettyTwo.vo.ChatMessage;
import com.linjiahao.servicebase.common.RedisService;
import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @ClassName RabbitReceiver
 * @Description: rabbit消息监听消费处理
 * @Author linjiahao
 * @Date 26/12/2021
 **/
@Component
@Slf4j
public class RabbitReceiver {

    @Resource
    private RedisService redisService;


    @RabbitListener(queues = "#{autoDeleteQueue1.name}")
    public void receiver1(String message) {
        log.info("监听到的消息为：{}",message);
        ChatMessage chatMessage = JSON.parseObject(message, ChatMessage.class);
        Object channleId = redisService.hget(ChannelHandlerPool.channelUserKey, chatMessage.getReceiverId());
        if(channleId ==null){
            log.info("用户离线：{},消息id为：{}",chatMessage.getReceiverId(),chatMessage.getMessageId());
            return;
        }
        Channel channel = ChannelHandlerPool.channelGroup.find((ChannelId)channleId);
        if(channel!=null){
            channel.writeAndFlush(new TextWebSocketFrame(chatMessage.getMessage()));
            log.info("消费成功,消息id为：{}",chatMessage.getMessageId());
            //展示模拟发送消息成功，记录起来
            redisService.hdel(ChannelHandlerPool.userMessageKey,chatMessage.getReceiverId());
        }
    }
}
